package com.rs.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CommonUtil {

    public static String getMD5(File file) {
        String md5 = "";
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            md5 = DigestUtils.md5Hex(in);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return md5;
    }

    public static void copyFile(String sourcePath, String targetPath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(sourcePath);
            FileUtil.writeFromStream(fis, targetPath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(fis);
        }
    }

    /**
     * 切割文件 分片
     *
     * @param src       源文件
     * @param begin     切割始点
     * @param blockSize 切割长度,也是分块的长度
     * @return 切割到的文件片
     */
    public static byte[] subBytes(byte[] src, int begin, int blockSize) {
        //一块分片是多大
        byte[] bytes = new byte[blockSize];
        System.arraycopy(src, begin, bytes, 0, begin + blockSize - begin);
        return bytes;
    }
}
